<!--
  * 产品领用出库表
  *
  * @Author:    zzw
  * @Date:      2024-10-09 15:08:50
  * @Copyright  jz
-->
<template>

    <div>
        <a-modal :title="form.id ? '编辑' : '添加'" width="60%" :open="visibleFlag" @cancel="onClose" :maskClosable="false"
            :destroyOnClose="true">
            <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">

                <a-row>
                    <a-col :span="12">
                        <a-form-item label="项目" name="projectId">
                            <a-select v-model:value="form.projectId" style="width: 100%" :options="projectOptions"
                                placeholder="项目"></a-select>

                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="用途" name="useExplain">
                            <a-input style="width: 100%" v-model:value="form.useExplain" placeholder="用途" />
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item label="审批人" name="approverId">
                            <a-select v-model:value="form.approverId" placeholder="审批人" :allowClear="true">
                                <a-select-option v-for="item in dictValueList" :key="item" :value="item.employeeId">
                                    {{ item.actualName }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="关联产品" name="code">
                            <a-input-search v-model:value="form.code" placeholder="关联产品" @search="onSearch" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-tabs activeKey="1">
                            <a-tab-pane key="1" tab="出库产品清单">
                                <a-table :dataSource="dataSource3" :columns="columns3" rowKey="goodsId" bordered
                                    :pagination="false"
                                    :rowSelection="{ selectedRowKeys: selectedRowKeysArray, onChange: onSelectChange3 }">
                                    <template #bodyCell="{ text, record, column, index }">
                                        <template v-if="column.dataIndex === 'index'">
                                            {{ index + 1 }}
                                        </template>
                                        <template v-if="column.dataIndex === 'usageQuantity'">
                                            <a-input-number :min="0"
                                                v-model:value="record.usageQuantity"></a-input-number>
                                        </template>

                                    </template>
                                </a-table>
                            </a-tab-pane>
                        </a-tabs>
                    </a-col>

                </a-row>
            </a-form>

            <template #footer>
                <a-space v-if="form.type != 3">
                    <a-button @click="onClose">取消</a-button>
                    <a-button type="primary" @click="onSubmit">保存</a-button>
                </a-space>
            </template>
        </a-modal>

        <a-modal v-model:open="goodsOpen" title="商品" width="60%" @ok="halderok">
            <a-table :dataSource="dataSource2" :columns="columns2" rowKey="goodsId" bordered :pagination="false"
                :scroll="{ y: 1100 }"
                :rowSelection="{ selectedRowKeys: selectedRowKeysArray, onChange: onSelectChange, }">
            </a-table>
        </a-modal>
    </div>

</template>
<script setup>
import { reactive, ref, nextTick } from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { usageOutboundApi } from '/@/api/business/outbound/api';
import { purchaseOrderApi } from '/@/api/business/purchase/index';
import { smartSentry } from '/@/lib/smart-sentry';
import { dictApi } from '/src/api/support/dict-api';
// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);


function onSelectChange(selectedRowKeys, selectedRows) {
    form.code = selectedRows[0].code
    for (let i = 0; i < selectedRows.length; i++) {
        selectedRows[i].usageQuantity = 0
    }
    dataSource3.value = selectedRows

}

function halderok() {
    goodsOpen.value = false
}

function onSelectChange3(selectedRowKeys, selectedRows) {
    form.usageOutboundGoodsListAddForms = selectedRows
}

const columns2 = ref([
    {
        title: '分类名称',
        dataIndex: 'categoryName',

        ellipsis: true,
    },
    {
        title: '编码',
        dataIndex: 'code',
        width: 120,
        ellipsis: true,
    },
    {
        title: '名称',
        dataIndex: 'goodsName',
        width: 120,
        ellipsis: true,
    },
    {
        title: '型号',
        dataIndex: 'model',

        ellipsis: true,
    },
    {
        title: '参数',
        dataIndex: 'parameter',

        ellipsis: true,
    },
    {
        title: '价格',
        dataIndex: 'price',

        ellipsis: true,
    },
]);
const columns3 = ref([
  
    {
        title: '产品编码',
        dataIndex: 'code',
        width: 120,
        ellipsis: true,
    },
    {
        title: '产品名称',
        dataIndex: 'goodsName',
        width: 120,
        ellipsis: true,
    },
    {
        title: '当前库存',
        dataIndex: 'currentStock',
        width: 120,
        ellipsis: true,
    },
    {
        title: '领用数量',
        dataIndex: 'usageQuantity',
        width: 120,

    },
    // /领用产品数量
    //currentStock
    {
        title: '型号',
        dataIndex: 'model',

        ellipsis: true,
    },
    {
        title: '参数',
        dataIndex: 'parameter',

        ellipsis: true,
    },
    {
        title: '价格',
        dataIndex: 'price',

        ellipsis: true,
    },
]);
const dataSource2 = ref([])
const dataSource3 = ref([])
const goodsOpen = ref(false)
function onSearch() {
    getGoodsqueryAll()
    goodsOpen.value = true
}

async function getGoodsqueryAll() {
    let res = await usageOutboundApi.getGoodsqueryAll();
    if (res.code == 0) {
        dataSource2.value = res.data
    }
}

// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {
    dataSource3.value = []
    getProject()
    queryDict()
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
        Object.assign(form, rowData);
    }
    visibleFlag.value = true;
    form.code = rowData.usageOutboundGoodsListVOS[0].code
    dataSource3.value = rowData.usageOutboundGoodsListVOS
    nextTick(() => {
        formRef.value.clearValidate();
    });
}

function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
}

// 获取项目下拉
const projectOptions = ref([])
function getProject() {
    purchaseOrderApi.project().then(res => {
        projectOptions.value = res.data.map(element => {
            return {
                label: element.customerName,
                value: element.id
            }
        })
    })
}

const dictValueList = ref([])
async function queryDict() {
    let res = await dictApi.ProjecPersonid();
    dictValueList.value = res.data;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
    id: undefined,
    projectId: undefined, //产品领用项目ID
    useExplain: undefined, //用途
    usageQuantity: undefined,
    code: undefined,
    approverId: undefined,
    approverName: undefined,
    usageOutboundGoodsListAddForms: undefined
};

let form = reactive({ ...formDefault });

const rules = {
    projectId: [{ required: true, message: '产品领用项目ID 必填' }],
    useExplain: [{ required: true, message: '用途 必填' }],
};

// 点击确定，验证表单
async function onSubmit() {
    let obj = dictValueList.value.filter((e) => {
        return e.employeeId == form.approverId
    })
    form.approverName = obj[0].actualName
    try {
        await formRef.value.validateFields();
        save();
    } catch (err) {
        message.error('参数验证错误，请仔细填写表单数据!');
    }
}

// 新建、编辑API
async function save() {
    SmartLoading.show();
    try {
        if (form.id) {
            await usageOutboundApi.update(form);
        } else {
            await usageOutboundApi.add(form);
        }
        message.success('操作成功');
        emits('reloadList');
        onClose();
    } catch (err) {
        smartSentry.captureError(err);
    } finally {
        SmartLoading.hide();
    }
}

defineExpose({
    show,
});
</script>